package com.lovo.ssc.service.impl;

import com.alibaba.fastjson.JSON;
import com.lovo.ssc.dto.WebCommodityDto;
import com.lovo.ssc.interceptor.CartInterceptor;
import com.lovo.ssc.service.ICommodityService;
import com.lovo.ssc.vo.Cart;
import com.lovo.ssc.vo.CartItem;
import com.lovo.ssc.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 购物车服务类
 * @author WXL
 * @date 2022/7/7
 */
@Service
public class CartService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ICommodityService commodityService;


    /**
     * 获取购物车的键
     * @return
     */
    private String getKey(){
        UserVo userVo = CartInterceptor.thread.get();
        String key = userVo.getUserId().toString();
        return key;
    }

    /**
     * 操作购物车
     * @return
     */
    private BoundHashOperations<String,Object,Object> getCartOps() {
        //绑定hash key
        BoundHashOperations<String,Object,Object> hashOps = redisTemplate.boundHashOps(this.getKey());
        return hashOps;
    }

    /**
     * 获取当前键的商品对象
     * @param goodsCode
     * @return
     */
    private CartItem getCartItem(String goodsCode){
        BoundHashOperations<String,Object,Object> cartOps = getCartOps();
        String str = (String) cartOps.get(goodsCode);
        //将字符串对象转换为对象
        CartItem cartItem = JSON.parseObject(str,CartItem.class);
        return cartItem;
    }

    public Cart findByCart(){
        BoundHashOperations<String,Object,Object> cartOps = getCartOps();
        List<Object> values = cartOps.values();
        List<CartItem> cartItemList = new ArrayList<>();
        for (Object o : values) {
            CartItem cartItem = JSON.parseObject((String) o, CartItem.class);
            cartItemList.add(cartItem);
        }
        Cart cart = new Cart();
        cart.setCartItemList(cartItemList);
        return cart;
    }

    public CartItem addToCart(String goodsCode, Integer buyNum) {
        BoundHashOperations<String,Object,Object> cartOps = getCartOps();
        String str =(String) cartOps.get(goodsCode);
        //如果购物车没有该商品
        if (StringUtils.isEmpty(str)) {
            //本地查询要添加的商品信息
            WebCommodityDto commodity = (WebCommodityDto) commodityService.findCommodity(goodsCode);
            CartItem item = new CartItem();
            item.setCheck(true);
            item.setGoodsCode(goodsCode);
            item.setBuyNum(buyNum);
            item.setGoodsName(commodity.getCommodityname());
            List<String> imgPathList = commodity.getImgpathList();
            item.setImg(imgPathList.get(0));
            item.setGoodsPrice(Float.valueOf(String.valueOf(commodity.getPrice())));
            item.setNorms(commodity.getNorms());
            item.setGoodsType(commodity.getType());
            //获取批次
            List<String> batchByCode = commodityService.findBatchByCode(goodsCode, buyNum);
            item.setGoodsBatch(batchByCode);

            String s = JSON.toJSONString(item);
            cartOps.put(goodsCode, s);
            return item;
        }else {
            //购物车有该商品
            CartItem item = JSON.parseObject(str, CartItem.class);
            item.setBuyNum(item.getBuyNum() + buyNum);
            //将对象转为json字符串
            cartOps.put(goodsCode,JSON.toJSONString(item));
            return item;
        }
    }

    public void delGoodsById(String goodsCode){
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(goodsCode);
    }

    public void clearCart(){
        redisTemplate.delete(this.getKey());
    }

    public void updateGoodsNumById(String goodsCode, Integer buyNum){
        CartItem item = getCartItem(goodsCode);
        item.setBuyNum(buyNum);
        String s = JSON.toJSONString(item);
        BoundHashOperations<String,Object,Object> cartOps = getCartOps();
        cartOps.put(goodsCode,s);
    }

    /**
     * 选中商品项
     * @return
     */
    public List<CartItem> findCheckItem(){
        Cart byCart = this.findByCart();
        List<CartItem> cartItemList = byCart.getCartItemList();
        List<CartItem> collect = cartItemList.stream().filter(item -> item.isCheck())
                .collect(Collectors.toList());
        return collect;
    }

    public void updateCheck(String goodsCode,boolean check){
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = this.getCartItem(goodsCode);
        cartItem.setCheck(check == true?false :true);
        String str = JSON.toJSONString(cartItem);
        cartOps.put(goodsCode,str);
    }
}
